package com.kulian.Signalling.system.service.impl.socket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kulian.Signalling.system.mode.socket.SignalingMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class MessageSender {
    private final SimpMessagingTemplate messagingTemplate;
    private final ObjectMapper objectMapper;

    public void sendToUser(String username, SignalingMessage message) {
        try {
            messagingTemplate.convertAndSendToUser(username, "/queue/signaling", message);
            log.debug("Message sent [{} -> {}] type: {}", 
                message.getFrom(), username, message.getType());
        } catch (Exception e) {
            log.error("Failed to send message [{}]: {}", username, e.getMessage());
        }
    }

    public void sendError(String username, String error) {
        SignalingMessage message = new SignalingMessage();
        message.setType("ERROR");
        message.setData(error);
        message.setTimestamp(System.currentTimeMillis());
        
        if (username != null && !username.isEmpty()) {
            sendToUser(username, message);
        } else {
            log.warn("Cannot send error - username is empty");
        }
    }

    public void broadcast(String destination, Object payload) {
        try {
            messagingTemplate.convertAndSend(destination, payload);
            log.debug("Broadcast message sent to {}", destination);
        } catch (Exception e) {
            log.error("Failed to broadcast message to {}: {}", destination, e.getMessage());
        }
    }

    public void sendToUser(String username, String destination, Object payload) {
        try {
            messagingTemplate.convertAndSendToUser(username, destination, payload);
            log.debug("Message sent [{} -> {}]", destination, username);
        } catch (Exception e) {
            log.error("Failed to send message [{} -> {}]: {}", 
                destination, username, e.getMessage());
        }
    }
}
